<?php
namespace other\orders\fx;
use other\PayPalMethod;
use other\ShopingConn;
use other\Table;
use think\Cache;
use think\Db;


// 空中云汇
class Airwallex
{
    public $AppointId = [
//        0 => 11641,
//        1 => 12172,
//        2 => 12305,
//        3 => 12362,
    ];

    public $AppointOrderSn = [
//        '#48553',
//        '#48497',
    ];

    public $FilterId = [];

    public $FilterPaypalOrderId = [
        // 拒付
        // 手动退款 (没查出来)
        // 失败
    ];

    private $PData = [];

    private function names($v){
        $key = md5(__METHOD__);
        $var = Cache::get($key);
        if (!$var){
            Cache::set($key,[$v]);
        }else{
            if(!in_array($v,$var)){
                $var[] = $v;
                Cache::set($key,$var);
            }
        }

        return $var;
    }


    /**
     * 处理
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function do()
    {
//        foreach ($this->FilterPaypalOrderId as &$v) $v = trim($v);
//        $column = ShopingConn::getConn()->table(Table::Table_Order)->where('paypal_order_id', 'in', $this->FilterPaypalOrderId)->column('id');
//        var_export($column);
//        exit();

        // 分析   // todo 只处理 一周前创建的订单 (因为1对多，可能新的状态还未出现)
        $start_time = time() - 3600 * 24 * 3;
        $time = time();
        $query = ShopingConn::getConn()
            ->table(Table::Table_Order_Notify_Logs);

        // 是否根据分析字段过滤(默认是，当有指定的字段时，是否)
        $is_filter_fx = true;
        // 当有定向订单要处理时
        if ($this->AppointId)
        {
            $is_filter_fx = false;
            $query = $query->where('order_id','in',$this->AppointId);
        }

        if ($this->AppointOrderSn)
        {
            $is_filter_fx = false;
            $order_ids = ShopingConn::getConn()->table(Table::Table_Order)
                ->where('order_sn','in',$this->AppointOrderSn)
                ->whereOr('payment_id','in',$this->AppointOrderSn)
                ->whereOr('payer_id','in',$this->AppointOrderSn)
                ->column('id');
            if ($order_ids){
                $query = $query->where('order_id','in',$order_ids);
            }
        }

        if ($is_filter_fx){
            $query = $query->where('is_fx', 0)
                ->where('created_at','between',[$start_time,$time]);
        }

        $order_ids = $query
            ->group('order_id')
            ->column('order_id');

        if ($order_ids)
        {
            foreach ($order_ids as $order_id)
            {
                if ($order_id)
                {
                    // 过滤 订单ID
                    if ($this->FilterId){
                        if (in_array($order_id,$this->FilterId)) continue;
                    }
                    $order_paypal_method = ShopingConn::getConn()
                        ->table(Table::Table_Order)
                        ->where('id',$order_id)
                        ->value('paypal_method');

                    //  支付类型不匹配
                    if ($order_paypal_method == PayPalMethod::Airwallex)
                    {
                        $datas = ShopingConn::getConn()
                            ->table(Table::Table_Order_Notify_Logs)
                            ->where('order_id',$order_id)
                            ->order('id','desc')
                            ->select();

                        if ($datas)
                        {
                            // 当前数据库中，该订单的状态
                            $status = ShopingConn::getConn()->table(Table::Table_Order)->where('id',$order_id)->value('status');
                            $paypal_order_id = ShopingConn::getConn()->table(Table::Table_Order)->where('id',$order_id)->value('paypal_order_id');

                            // 过滤 paypal_order_id
                            if($this->FilterPaypalOrderId){
                                if (in_array($paypal_order_id,$this->FilterPaypalOrderId)) continue;
                            }

                            $ids = array_column($datas,'id');

                            $xh = 0;

                            $names_arr = [];
                            while ($row = array_pop($datas))
                            {
                                $xh++;
                                $params = $row['params'];
                                $params = json_decode($params,true);
//                                var_export($params);
//                                exit();
                                $name = empty($params['name'])?'':$params['name'];
                                $createdAt = empty($params['createdAt'])?0:date('Y-m-d H:i:s',strtotime($params['createdAt']));
                                if ($name){

                                    // 副文案
                                    switch ($name){
                                        case 'payment_dispute.accepted':$msg = format\Airwallex::payment_dispute_accepted($params);break;
                                        case 'payment_dispute.requires_response':$msg = format\Airwallex::payment_dispute_requires_response($params);break;
                                        case 'payment_attempt.authorization_failed':$msg = format\Airwallex::payment_attempt_authorization_failed($params);break;
                                        case 'payment_attempt.risk_declined':$msg = format\Airwallex::payment_attempt_risk_declined($params);break;
                                        default:$msg='';
                                    }
                                    $msg .= '('.$createdAt.')';

                                    $name_msg = empty(format\Airwallex::$names[$name])?$name:format\Airwallex::$names[$name];
//                                    $names_arr[$xh] = '['.$xh.']'.$name_msg.$msg;
                                    $names_arr[$xh] = $name_msg.$msg;
                                    $this->names($name);
                                }else{
//                                    if ($params){
//                                        var_export($params);
//                                        exit();
//                                    }
                                }
                            }

                            $descs = format\Airwallex::order($names_arr);
                            $oid = $order_id.'-'.$paypal_order_id;

                            $this->_process($order_id,$descs,$oid);
                            $this->_ex_abnormal_orders(1,$order_id,$ids);

                            // 排序
//                            $this->PData[$xh_total.'-'.$order_id.'-'.$paypal_order_id] = format\Airwallex::order($names_arr);
                        }
                    }
                }
            }
        }



//        var_export(format\Airwallex::$all);
//        exit();


//        foreach ($this->PData as $oid => $descs){
//
//            echo $oid.':'.implode('--',$descs)."\r\n";
//        }


//        var_export($this->PData);
//        var_export($this->names('aaa'));
    }


    /**
     * 分析出订单的状态后更改
     * @param $abnormal_orders
     * @param $order_id
     * @param $ids
     * @return void
     * @throws Exception
     * @throws PDOException
     */
    private function _ex_abnormal_orders($abnormal_orders,$order_id,$ids)
    {
        Db::transaction(function ()use($abnormal_orders,$order_id,$ids){
            ShopingConn::getConn()->table(Table::Table_Order)->where('id',$order_id)->update(['abnormal_orders' => $abnormal_orders]);

            foreach ($ids as $id){
                ShopingConn::getConn()->table(Table::Table_Order_Notify_Logs)->where('id',$id)->update(['is_fx' => 1]);
            }
        });
    }

    /**
     * 进程 回填
     * @param $order_id
     * @param $descs
     * @param $oid
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function _process($order_id,$descs,$oid){
        $value = ShopingConn::getConn()->table(Table::Table_orders_payment_process)->where('order_id', $order_id)->value('process');
        if ($value){
            $process = $value.'--'.implode('--',$descs);
            ShopingConn::getConn()->table(Table::Table_orders_payment_process)->where('order_id', $order_id)->update(compact("process"));
        }else{
            $process = $oid.':'.implode('--',$descs);
            ShopingConn::getConn()->table(Table::Table_orders_payment_process)->insert(compact("process","order_id"));
        }
    }

}
